package com.ibm.cloud.banking.sample.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.cloud.banking.platform.context.service.RequestContextHandler;
import com.ibm.cloud.banking.sample.dto.OeRequestLogDTO;
import com.ibm.cloud.banking.sample.service.IPcsLogService;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

import lombok.extern.slf4j.Slf4j;

/**
 * replace desc in here
 *
 * @author HanDong
 * @date 2022/7/26
 */
@Aspect
@Component
@Slf4j
public class PcsLogAspect {

    @Autowired
   private IPcsLogService pcsLogService;

    //定义切点
    @Pointcut(value = "execution(* com.ibm.cloud.banking.platform.controller.PcsController.*(..))")
    public void aopPcsLog() {
    }

    /**
     * 环绕切入
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("aopPcsLog()")
    public Object pcsLogger(ProceedingJoinPoint pjp) throws Throwable {

        Object[] array = pjp.getArgs();
        ObjectMapper mapper = new ObjectMapper();


        String id = UUID.randomUUID().toString();
        OeRequestLogDTO oeRequestLogDTO =  OeRequestLogDTO
                .builder()
                .id(id)
                        .request(mapper.writeValueAsString(array))
                                .build();
        pcsLogService.saveLog(oeRequestLogDTO);
        /**
         * TODO 子线程上下文开启清理临时处理...
         */
        RequestContextHandler.initInheritableThreadLocal();
        Object obj = pjp.proceed();
        RequestContextHandler.cleanInheritableThreadLocal();
        pcsLogService.updateLog(id, mapper.writeValueAsString(obj));
        return obj;
    }


}
